package ETLLOG;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

/**
 * Created by yqz on 2019/3/30.
 *
 */
public class LoggerMapper extends Mapper<LongWritable, Text, Text, NullWritable> {
    Text k = new Text();

    @Override
    protected void map(LongWritable key,
                       Text value,
                       Context context) throws IOException, InterruptedException {
        //1.所有的数据值：Text ==> String
        //数据：1.162.203.134 - - [18/Sep/2013:13:47:35 +0000] "GET /images/my.jpg HTTP/1.1" 200 ...
        String line = value.toString();

        //2.解析日志
        //line : 参数1：数据
        //context:联系上下文，功能：实现计数器的功能
        boolean result = parseLog(line, context);

        //3.如果数据字段小于等于11的话，就返回
        if (!result) {
            return;
        }

        k.set(line);

        //4.context联系下文
        context.write(k, NullWritable.get());
    }

    /**
     * 2.解析日志
     * 日志长度大于11的话，就算为计数
     * true   计数
     * false  计数
     * 数据：1.162.203.134 - - [18/Sep/2013:13:47:35 +0000] "GET /images/my.jpg HTTP/1.1" 200 ...
     *
     * @param line
     * @param context
     * @return
     */
    private boolean parseLog(String line, Context context) {
        //1.截取
        //[1.162.203.134 - - [18/Sep/2013:13:47:35 +0000] "GET /images/my.jpg HTTP/1.1" 200 ...]
        String[] fields = line.split(" ");

        //2.判断是数据字段长度大于11
        if (fields.length > 11) {
            context.getCounter("map","true").increment(1);
            return true;
        }else {
            context.getCounter("map","false").increment(1);
            return false;
        }
    }

}
